package com.quanshu.exchange.ui.gui.profile;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.quanshu.change.login.view.ResetPasswordActivity;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.chat.ChatHelper;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.db.core.DBController;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.Util;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.login.LoginActivity;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.base.view.BaseTitleBar;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 设置
 * Created by xiniu003 on 2017/12/13.
 */

public class SettingActivity extends BaseActivity {

    @BindView(R.id.amend_enter_password_rel)
    RelativeLayout amendEnterPasswordRel;
    @BindView(R.id.setting_pay_password_rel)
    RelativeLayout editPayPasswordRel;
    @BindView(R.id.share_exchange)
    RelativeLayout shareExchange;
    @BindView(R.id.setting_title)
    BaseTitleBar settingTitle;
    @BindView(R.id.quit_enter1)
    TextView quitEnter1;

    private IWXAPI iwxapi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        iwxapi = WXAPIFactory.createWXAPI(this, MyApplication.getInstance().getWX_ID(), false);
        initView();
        initListener();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    private void initView() {
        ImmersionBar.with(this).titleBar(settingTitle).statusBarColor(R.color.white).statusBarDarkFont(true).init();
    }

    private void initListener() {

        settingTitle.setLeftImage(R.drawable.icon_back_black_2_0).setCenterText("设置").setOnClickBaseTitleListener(new BaseTitleBar.OnClickBaseTitleBarListener() {
            @Override
            public void onclickLeft() {
                finish();
            }

            @Override
            public void onclickRight() {

            }
        });

        //修改登录密码
        RxViewHelper.getInstance().clicks(amendEnterPasswordRel, aVoid -> {
//            Intent intent = new Intent(SettingActivity.this, AmendEnterPasswordActivity.class);
//            startActivity(intent);
            BaseTool.goActivity(this, ResetPasswordActivity.class,null);

        });

        //设置支付密码
        RxViewHelper.getInstance().clicks(editPayPasswordRel, aVoid -> {
            Intent intent = new Intent(SettingActivity.this, SetPayPasswordActivity.class);
            startActivityForResult(intent, 7);
        });

        //分享
        RxViewHelper.getInstance().clicks(shareExchange, aVoid -> {
            doShowShareDialog();
        });


        //退出登录
        RxViewHelper.getInstance().clicks(quitEnter1, aVoid -> doLogout());
    }

    private void doShowShareDialog() {
        String webUrl = Config.SHARE_APP_URL;//供分享的下载链接
        String weChat = "weChat";//微信
        String friends = "friends";//朋友圈
        DialogShare dialogShare = new DialogShare(this);
        dialogShare.show();

        //分享到微信
        dialogShare.getWeChatSubject().subscribe(o -> {
            doShareWeChat(webUrl, weChat);
            dialogShare.cancel();
        });

        //分享到朋友圈
        dialogShare.getFriendsSubject().subscribe(o -> {
            doShareWeChat(webUrl, friends);
            dialogShare.cancel();
        });
    }

    private void doShareWeChat(String webUrl, String type) {

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = webUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "牛兑换";
        msg.description = "我最喜欢的App";
        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        msg.thumbData = Util.bmpToByteArray(thumb, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        if (type.equals("weChat")) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else if (type.equals("friends")) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        iwxapi.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private void doLogout() {
        doLoginOut();
        DBController.reset();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 7 && resultCode == 1) {
            editPayPasswordRel.setVisibility(View.VISIBLE);
        }
    }

    private void doLoginOut() {
        ChatHelper.getInstance().logout(true, null);
        MyApplication.getInstance().setCurrentUser(null);
        currentUser = null;
        Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
//        NetClient.getInstance()
//                .getShopService(LoginInterface.class)
//                .logOut()
//                .compose(new BaseTransformer<>(this))
//                .subscribe(new BaseObserver<BaseResponse>() {
//                    @Override
//                    public void onSuccess(BaseResponse response) {
//                        ChatHelper.getInstance().logout(true, null);
//                        MyApplication.getInstance().setCurrentUser(null);
//                        currentUser = null;
//                        Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
//                        finish();
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        ChatHelper.getInstance().logout(true, null);
//                        Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
//                        finish();
//                    }
//                });
    }

}
